<template>
  <div class="payment-management">
    <a-spin :loading="loading">
      <!-- 镇街支付明细列表 -->
      <div class="town-payment-details">
        <div class="section-header">
          <div class="section-left">
            <h3 class="section-title">镇街支付明细</h3>
            <a-select
              v-model="selectedNoticeId"
              placeholder="请选择支付通知"
              style="width: 300px; margin-left: 16px"
              @change="handleNoticeChange"
            >
              <a-option
                v-for="notice in paymentNotices"
                :key="notice.subsidyApplicationPayNoticeId"
                :value="notice.subsidyApplicationPayNoticeId"
              >
                {{ notice.payExplain }}
              </a-option>
            </a-select>
          </div>
          <a-button
            type="outline"
            :loading="refreshLoading"
            @click="refreshData"
          >
            <template #icon><IconRefresh /></template>
            刷新
          </a-button>
        </div>

        <a-spin :loading="townDetailsLoading">
          <div v-if="sortedTownDetails.length > 0" class="town-details-list">
            <a-card
              v-for="(town, index) in sortedTownDetails"
              :key="index"
              class="town-detail-card"
              :title="town.townName"
            >
              <template #extra>
                <a-button
                  type="primary"
                  size="small"
                  @click="showAddPaymentRecord(town)"
                >
                  <template #icon><IconPlus /></template>
                  添加支付记录
                </a-button>
              </template>

              <div class="town-info-line">
                <span class="info-item">
                  <strong>验收亩数:</strong> {{ town.acceptAcreage || 0 }}亩
                </span>
                <span class="separator">|</span>
                <span class="info-item">
                  <strong>总金额:</strong> {{ town.totalAmount || 0 }}万元
                </span>
                <span class="separator">|</span>
                <span class="info-item">
                  <strong>支付比例:</strong> {{ town.paymentRadio || 0 }}%
                </span>
                <span class="separator">|</span>
                <span class="info-item">
                  <strong>当前支付金额:</strong>
                  <span class="current-amount-text"
                    >{{ town.currentPaymentAmount || 0 }}万元</span
                  >
                </span>
                <span v-if="town.remark" class="separator">|</span>
                <span v-if="town.remark" class="info-item">
                  <strong>备注:</strong> {{ town.remark }}
                </span>
              </div>

              <!-- 该镇街的支付记录列表 -->
              <div
                v-if="getTownPaymentRecords(town).length > 0"
                class="town-payment-records"
              >
                <h4>支付记录</h4>
                <div class="payment-record-list">
                  <div
                    v-for="record in getTownPaymentRecords(town)"
                    :key="record.subsidyApplicationPayRecordId"
                    class="payment-record-item"
                  >
                    <div class="record-content">
                      <span class="record-info">
                        <strong>{{ record.payMoney || 0 }}万元</strong>
                        <span class="separator">|</span>
                        <span>{{ record.payDate || "-" }}</span>
                        <span class="separator">|</span>
                        <span>{{
                          getPaymentMethodText(record.payMethod)
                        }}</span>
                        <span v-if="record.remark" class="separator">|</span>
                        <span v-if="record.remark" class="record-remark">{{
                          record.remark
                        }}</span>
                      </span>
                    </div>
                    <div class="record-actions">
                      <a-space>
                        <a-button
                          type="text"
                          size="small"
                          @click="editTownPaymentRecord(record)"
                        >
                          编辑
                        </a-button>
                        <a-popconfirm
                          content="确定要删除这条支付记录吗？"
                          @ok="deleteTownPaymentRecord(record)"
                        >
                          <a-button type="text" size="small" status="danger">
                            删除
                          </a-button>
                        </a-popconfirm>
                      </a-space>
                    </div>
                  </div>
                </div>
              </div>
            </a-card>
          </div>

          <a-empty v-else description="请选择支付通知查看镇街支付明细" />
        </a-spin>
      </div>
    </a-spin>

    <!-- 新增/编辑镇街支付记录弹窗 -->
    <a-modal
      v-model:visible="townPaymentModalVisible"
      :title="editingTownPayment ? '编辑支付记录' : '新增支付记录'"
      width="600px"
      :ok-loading="submitLoading"
      @ok="handleTownPaymentSubmit"
      @cancel="resetTownPaymentForm"
    >
      <a-form
        ref="townPaymentFormRef"
        :model="townPaymentForm"
        :rules="townPaymentRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="镇街名称">
              <a-input v-model="townPaymentForm.townName" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="支付金额(万元)" field="paymentAmount">
              <a-input
                v-model="townPaymentForm.paymentAmount"
                placeholder="输入支付金额"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="支付日期" field="paymentDate">
              <a-date-picker
                v-model="townPaymentForm.paymentDate"
                style="width: 100%"
                placeholder="选择支付日期"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="支付方式" field="paymentMethod">
              <a-select
                v-model="townPaymentForm.paymentMethod"
                placeholder="请选择支付方式"
              >
                <a-option
                  v-for="item in paymentMethods"
                  :key="item.dictKey"
                  :value="String(item.dictKey)"
                >
                  {{ item.dictValue }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="支付凭证">
              <!-- 上传组件 - 仅在没有已有附件时显示 -->
              <div v-if="!currentPaymentVoucher" class="upload-section">
                <uploadFile
                  ref="townPaymentUploadFile"
                  :file-source="
                    fileSource.lindi_subsidy_payment_record_file?.key
                  "
                  @upload-success="handleTownPaymentUploadSuccess"
                  accept="image/*,.pdf"
                  :limit="1"
                />
                <div class="upload-tip">
                  <IconInfo class="tip-icon" />
                  支持上传图片（JPG、PNG等）或PDF文件，文件大小不超过10MB
                </div>
              </div>

              <!-- 已上传支付凭证展示 -->
              <div
                v-if="currentPaymentVoucher"
                class="existing-voucher-section"
              >
                <div class="existing-voucher-title">已上传支付凭证</div>
                <div class="existing-voucher-item">
                  <div class="voucher-info">
                    <div class="voucher-icon">
                      <IconFile
                        v-if="!isImageFile(currentPaymentVoucher.fileName)"
                      />
                      <IconImage v-else />
                    </div>
                    <div class="voucher-details">
                      <p
                        class="voucher-name"
                        :title="currentPaymentVoucher.fileName"
                      >
                        {{ currentPaymentVoucher.fileName }}
                      </p>
                      <p
                        class="voucher-size"
                        v-if="currentPaymentVoucher.fileSize"
                      >
                        {{ formatFileSize(currentPaymentVoucher.fileSize) }}
                      </p>
                    </div>
                  </div>
                  <div class="voucher-actions">
                    <a-button
                      type="text"
                      size="small"
                      @click="downloadPaymentVoucher(currentPaymentVoucher)"
                    >
                      <template #icon><IconDownload /></template>
                      下载
                    </a-button>
                    <a-button
                      v-if="isImageFile(currentPaymentVoucher.fileName)"
                      type="text"
                      size="small"
                      @click="previewPaymentVoucher(currentPaymentVoucher)"
                    >
                      <template #icon><IconEye /></template>
                      预览
                    </a-button>
                    <a-button
                      type="text"
                      size="small"
                      status="danger"
                      @click="removePaymentVoucher"
                    >
                      <template #icon><IconDelete /></template>
                      删除
                    </a-button>
                    <a-button
                      type="primary"
                      size="small"
                      @click="replacePaymentVoucher"
                    >
                      <template #icon><IconPlus /></template>
                      重新上传
                    </a-button>
                  </div>
                </div>
              </div>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="24">
            <a-form-item label="备注">
              <a-textarea
                v-model="townPaymentForm.remark"
                placeholder="输入支付备注"
                :auto-size="{ minRows: 2, maxRows: 4 }"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 支付凭证预览弹窗 -->
    <a-modal
      v-model:visible="voucherPreviewModalVisible"
      :title="previewVoucherFile?.fileName || '支付凭证预览'"
      width="80%"
      :footer="false"
    >
      <div class="preview-content">
        <img
          v-if="previewVoucherFile && isImageFile(previewVoucherFile.fileName)"
          :src="previewVoucherFile.fileUrl"
          :alt="previewVoucherFile.fileName || '预览图片'"
          class="preview-image"
        />
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import {
  onMounted,
  onUnmounted,
  reactive,
  ref,
  computed,
  h,
  getCurrentInstance,
} from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconPlus,
  IconFile,
  IconImage,
  IconDownload,
  IconEye,
  IconDelete,
  IconInfo,
  IconRefresh,
} from "@arco-design/web-vue/es/icon";
// 导入API接口
import {
  addSubsidyApplicationPayRecordApi,
  updateSubsidyApplicationPayRecordBySubsidyApplicationPayRecordIdApi,
  deleteSubsidyApplicationPayRecordBySubsidyApplicationPayRecordIdApi,
  getSubsidyApplicationPayRecordListBySubsidyApplicationIdApi,
} from "~/api/lindi/subsidyPayRecord.js";
import { getSubsidyApplicationPayNoticeListBySubsidyApplicationIdApi } from "~/api/lindi/subsidyApplicationPayNotice.js";
import { getSubsidyApplicationTownPaymentListBySubsidyApplicationPayNoticeIdApi } from "~/api/lindi/subsidyApplicationTownPayment.js";
import uploadFile from "~/components/uploadFile/index.vue";
import { fileSource } from "~/utils/sys.js";
import { deleteFileApi } from "~/api/basic/file.js";

// 定义props
const props = defineProps({
  subsidyApplicationId: {
    type: String,
    required: true,
  },
});

// 全局实例
const { proxy } = getCurrentInstance();

// 字典数据
const dicts = proxy.LoadDicts([proxy.DICT.lindiPaymentMethod]);

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const townDetailsLoading = ref(false);
const refreshLoading = ref(false);
const paymentNotices = ref([]);
const selectedNoticeId = ref(null);
const currentTownDetails = ref([]);

// 镇街支付记录相关状态
const townPaymentModalVisible = ref(false);
const editingTownPayment = ref(false);
const townPaymentFormRef = ref(null);
const townPaymentRecords = ref([]);
const currentSelectedTown = ref(null);

// 支付凭证相关状态
const currentPaymentVoucher = ref(null);
const voucherPreviewModalVisible = ref(false);
const previewVoucherFile = ref(null);
const newUploadedFileIds = ref([]);

// 镇街支付记录表单数据
const townPaymentForm = reactive({
  recordId: "",
  townName: "",
  paymentAmount: null,
  paymentDate: null,
  paymentMethod: null,
  paymentVoucherFileId: null,
  remark: "",
});

// 表单验证规则
const townPaymentRules = {
  paymentAmount: [{ required: true, message: "请输入支付金额" }],
  paymentDate: [{ required: true, message: "请选择支付日期" }],
  paymentMethod: [{ required: true, message: "请选择支付方式" }],
};

// 支付方式列表 - 使用字典数据
const paymentMethods = computed(() => {
  return dicts[proxy.DICT.lindiPaymentMethod] || [];
});

// 按当前支付金额倒序排列的镇街支付明细，并过滤掉支付金额为0的记录
const sortedTownDetails = computed(() => {
  if (!Array.isArray(currentTownDetails.value)) {
    return [];
  }
  return [...currentTownDetails.value]
    .filter((town) => {
      const amount = parseFloat(town.currentPaymentAmount) || 0;
      return amount > 0; // 只显示支付金额大于0的记录
    })
    .sort((a, b) => {
      const amountA = parseFloat(a.currentPaymentAmount) || 0;
      const amountB = parseFloat(b.currentPaymentAmount) || 0;
      return amountB - amountA; // 倒序排列
    });
});

// 镇街支付记录表格列定义
const townPaymentColumns = [
  {
    title: "支付金额(万元)",
    dataIndex: "payMoney",
    width: 120,
  },
  {
    title: "支付日期",
    dataIndex: "payDate",
    width: 120,
  },
  {
    title: "支付方式",
    dataIndex: "payMethod",
    width: 100,
    render: ({ record }) => {
      return getPaymentMethodText(record.payMethod);
    },
  },
  {
    title: "支付凭证",
    dataIndex: "fileId",
    width: 100,
    render: ({ record }) => {
      return record.fileId
        ? h(
            "a-button",
            {
              type: "text",
              size: "small",
              onClick: () => viewPaymentVoucher(record),
            },
            "查看凭证"
          )
        : "-";
    },
  },
  {
    title: "备注",
    dataIndex: "remark",
    width: 150,
  },
  {
    title: "操作",
    slotName: "action",
    width: 120,
    align: "center",
  },
];

// 镇街明细表格列定义
const townDetailsColumns = [
  {
    title: "镇街名称",
    dataIndex: "townName",
    key: "townName",
  },
  {
    title: "受理面积(亩)",
    dataIndex: "acceptAcreage",
    key: "acceptAcreage",
  },
  {
    title: "总金额(万元)",
    dataIndex: "totalAmount",
    key: "totalAmount",
  },
  {
    title: "支付比例(%)",
    dataIndex: "paymentRadio",
    key: "paymentRadio",
  },
  {
    title: "本次支付金额(万元)",
    dataIndex: "currentPaymentAmount",
    key: "currentPaymentAmount",
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
  },
  {
    title: "操作",
    key: "action",
    render: ({ record }) => [
      h(
        "a-button",
        {
          type: "primary",
          size: "small",
          onClick: () => openTownPaymentModal(record),
        },
        "添加支付记录"
      ),
    ],
  },
];

// 获取指定镇街的支付记录 - 使用computed优化性能
const townPaymentRecordsMap = computed(() => {
  const map = new Map();
  // 确保townPaymentRecords.value是数组
  if (Array.isArray(townPaymentRecords.value)) {
    townPaymentRecords.value.forEach((record) => {
      // 使用subsidyApplicationTownPaymentId作为关联键，如果没有则使用townName
      const key = record.subsidyApplicationTownPaymentId || record.townName;
      if (!map.has(key)) {
        map.set(key, []);
      }
      map.get(key).push(record);
    });
  }
  return map;
});

const getTownPaymentRecords = (town) => {
  // 优先使用subsidyApplicationTownPaymentId，如果没有则使用townName
  const key = town.subsidyApplicationTownPaymentId || town.townName;
  return townPaymentRecordsMap.value.get(key) || [];
};

// 防抖定时器
let noticeChangeTimer = null;

// 处理支付通知变化 - 优化加载状态和防抖
const handleNoticeChange = async (noticeId) => {
  // 清除之前的定时器
  if (noticeChangeTimer) {
    clearTimeout(noticeChangeTimer);
  }

  if (noticeId) {
    townDetailsLoading.value = true;

    // 使用防抖，避免快速切换时的多次请求
    noticeChangeTimer = setTimeout(async () => {
      try {
        // 获取镇街支付明细
        const response =
          await getSubsidyApplicationTownPaymentListBySubsidyApplicationPayNoticeIdApi(
            noticeId
          );
        if (response) {
          currentTownDetails.value = Array.isArray(response) ? response : [];
          console.log("currentTownDetails.value", currentTownDetails.value);
        } else {
          currentTownDetails.value = [];
          Message.error("获取镇街支付明细失败");
        }

        // 同时加载该支付通知下的支付记录
        await loadTownPaymentRecordsByNoticeId(noticeId);
      } catch (error) {
        console.error("获取镇街支付明细失败:", error);
        currentTownDetails.value = [];
        Message.error("获取镇街支付明细失败");
      } finally {
        townDetailsLoading.value = false;
      }
    }, 300); // 300ms防抖延迟
  } else {
    currentTownDetails.value = [];
    townDetailsLoading.value = false;
  }
};

// 显示添加支付记录弹窗
const showAddPaymentRecord = (town) => {
  currentSelectedTown.value = town;
  resetTownPaymentForm(); // 这会清空所有表单数据包括文件ID
  townPaymentForm.townName = town.townName;
  editingTownPayment.value = false;
  townPaymentModalVisible.value = true;
};

// 编辑镇街支付记录
const editTownPaymentRecord = (record) => {
  // 确保currentTownDetails.value是数组
  currentSelectedTown.value = Array.isArray(currentTownDetails.value)
    ? currentTownDetails.value.find((town) => town.townName === record.townName)
    : null;
  townPaymentForm.recordId = record.subsidyApplicationPayRecordId;
  townPaymentForm.townName = record.townName;
  townPaymentForm.paymentAmount = record.payMoney;
  townPaymentForm.paymentDate = record.payDate;
  townPaymentForm.paymentMethod = record.payMethod;
  townPaymentForm.paymentVoucherFileId = record.fileId;
  townPaymentForm.remark = record.remark;

  // 加载已有的支付凭证信息
  if (record.fileId && record.file) {
    currentPaymentVoucher.value = {
      fileId: record.fileId,
      fileName: record.file.fileName,
      fileSize: record.file.fileSize,
      fileUrl: record.file.fileUrl,
    };
  } else {
    currentPaymentVoucher.value = null;
  }

  editingTownPayment.value = true;
  townPaymentModalVisible.value = true;
};

// 加载支付记录 - 优化loading状态管理
const loadTownPaymentRecords = async (showLoading = true) => {
  if (!props.subsidyApplicationId) return;

  try {
    if (showLoading) {
      loading.value = true;
    }
    const response =
      await getSubsidyApplicationPayRecordListBySubsidyApplicationIdApi(
        props.subsidyApplicationId
      );
    if (response) {
      // 确保townPaymentRecords.value始终是数组
      townPaymentRecords.value = Array.isArray(response) ? response : [];
      console.log("townPaymentRecords.value", townPaymentRecords.value);
    } else {
      townPaymentRecords.value = [];
      Message.error("获取支付记录失败");
    }
  } catch (error) {
    console.error("获取支付记录失败:", error);
    townPaymentRecords.value = [];
    Message.error("获取支付记录失败");
  } finally {
    if (showLoading) {
      loading.value = false;
    }
  }
};

// 根据支付通知ID加载支付记录
const loadTownPaymentRecordsByNoticeId = async (noticeId) => {
  if (!noticeId) {
    townPaymentRecords.value = [];
    return;
  }

  try {
    // 从支付通知列表中找到对应的支付通知，获取其支付记录
    const selectedNotice = paymentNotices.value.find(
      (notice) => notice.subsidyApplicationPayNoticeId === noticeId
    );

    if (selectedNotice && selectedNotice.payRecordList) {
      townPaymentRecords.value = Array.isArray(selectedNotice.payRecordList)
        ? selectedNotice.payRecordList
        : [];
      console.log("从支付通知加载的支付记录:", townPaymentRecords.value);
    } else {
      townPaymentRecords.value = [];
    }
  } catch (error) {
    console.error("加载支付记录失败:", error);
    townPaymentRecords.value = [];
  }
};

// 删除镇街支付记录
const deleteTownPaymentRecord = async (record) => {
  try {
    submitLoading.value = true;
    const response =
      await deleteSubsidyApplicationPayRecordBySubsidyApplicationPayRecordIdApi(
        record.subsidyApplicationPayRecordId
      );
    if (response) {
      // 重新加载镇街支付明细和支付记录数据
      if (selectedNoticeId.value) {
        await handleNoticeChange(selectedNoticeId.value);
      }
      Message.success("删除成功");
    } else {
      Message.error("删除失败");
    }
  } catch (error) {
    console.error("删除支付记录失败:", error);
    Message.error("删除失败");
  } finally {
    submitLoading.value = false;
  }
};

// 提交镇街支付记录表单
const handleTownPaymentSubmit = () => {
  return townPaymentFormRef.value
    .validate()
    .then(() => {
      submitLoading.value = true;

      const formData = {
        subsidyApplicationId: props.subsidyApplicationId,
        payType: "TOWN_PAYMENT",
        payMoney: townPaymentForm.paymentAmount,
        payDate: townPaymentForm.paymentDate,
        payMethod: townPaymentForm.paymentMethod,
        fileId: townPaymentForm.paymentVoucherFileId,
        remark: townPaymentForm.remark,
        subsidyApplicationPayNoticeId: selectedNoticeId.value,
        subsidyApplicationTownPaymentId:
          currentSelectedTown.value?.subsidyApplicationTownPaymentId,
        townName: townPaymentForm.townName,
      };

      if (editingTownPayment.value) {
        // 编辑现有记录
        formData.subsidyApplicationPayRecordId = townPaymentForm.recordId;
        return updateSubsidyApplicationPayRecordBySubsidyApplicationPayRecordIdApi(
          formData
        );
      } else {
        // 添加新记录
        return addSubsidyApplicationPayRecordApi(formData);
      }
    })
    .then((response) => {
      if (response) {
        Message.success(editingTownPayment.value ? "编辑成功" : "添加成功");
        // 重新加载镇街支付明细和支付记录数据
        if (selectedNoticeId.value) {
          return handleNoticeChange(selectedNoticeId.value);
        }
      } else {
        throw new Error("操作失败");
      }
    })
    .then(() => {
      // 提交成功后清理新上传文件ID列表
      newUploadedFileIds.value = [];
      townPaymentModalVisible.value = false;
      resetTownPaymentForm();
    })
    .catch((error) => {
      console.error("提交支付记录失败:", error);
      Message.error("操作失败");

      // 如果是新增记录且有上传的文件，则清理文件
      if (!editingTownPayment.value && townPaymentForm.paymentVoucherFileId) {
        deleteFileApi(townPaymentForm.paymentVoucherFileId)
          .then(() => {
            console.log("已清理上传的文件");
          })
          .catch((deleteError) => {
            console.error("清理文件失败:", deleteError);
          });
      }

      throw error;
    })
    .finally(() => {
      submitLoading.value = false;
    });
};

// 重置镇街支付记录表单
const resetTownPaymentForm = () => {
  townPaymentForm.recordId = "";
  townPaymentForm.townName = "";
  townPaymentForm.paymentAmount = null;
  townPaymentForm.paymentDate = null;
  townPaymentForm.paymentMethod = null;
  townPaymentForm.paymentVoucherFileId = null;
  townPaymentForm.remark = "";

  // 清空支付凭证相关数据
  currentPaymentVoucher.value = null;

  if (townPaymentFormRef.value) {
    townPaymentFormRef.value.resetFields();
  }
};

// 处理文件上传成功
const handleTownPaymentUploadSuccess = (fileInfo) => {
  townPaymentForm.paymentVoucherFileId = fileInfo.fileId;
  // 保存当前上传的支付凭证信息
  currentPaymentVoucher.value = {
    fileId: fileInfo.fileId,
    fileName: fileInfo.fileName,
    fileSize: fileInfo.fileSize,
    fileUrl: fileInfo.fileUrl,
  };
  // 记录新上传的文件ID，用于清理
  newUploadedFileIds.value.push(fileInfo.fileId);
  Message.success("支付凭证上传成功");
};

// 判断是否为图片文件
const isImageFile = (fileName) => {
  if (!fileName) return false;
  const imageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"];
  const extension = fileName.toLowerCase().substring(fileName.lastIndexOf("."));
  return imageExtensions.includes(extension);
};

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return "-";
  const units = ["B", "KB", "MB", "GB"];
  let index = 0;
  let fileSize = parseFloat(size);

  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024;
    index++;
  }

  return `${fileSize.toFixed(1)} ${units[index]}`;
};

// 下载支付凭证
const downloadPaymentVoucher = (voucher) => {
  if (voucher?.fileUrl) {
    const link = document.createElement("a");
    link.href = voucher.fileUrl;
    link.download = voucher.fileName || "支付凭证";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    Message.error("文件下载链接不存在");
  }
};

// 预览支付凭证
const previewPaymentVoucher = (voucher) => {
  if (voucher && isImageFile(voucher.fileName)) {
    previewVoucherFile.value = voucher;
    voucherPreviewModalVisible.value = true;
  } else {
    Message.warning("该文件类型不支持预览");
  }
};

// 删除支付凭证
const removePaymentVoucher = async () => {
  if (!currentPaymentVoucher.value?.fileId) return;

  const fileId = currentPaymentVoucher.value.fileId;

  try {
    await deleteFileApi(fileId);
    // 清空相关数据
    townPaymentForm.paymentVoucherFileId = null;
    currentPaymentVoucher.value = null;
    // 从新上传文件列表中移除
    const index = newUploadedFileIds.value.indexOf(fileId);
    if (index > -1) {
      newUploadedFileIds.value.splice(index, 1);
    }
    Message.success("支付凭证删除成功");
  } catch (error) {
    console.error("删除支付凭证失败:", error);
    Message.error("删除支付凭证失败");
  }
};

// 重新上传支付凭证
const replacePaymentVoucher = async () => {
  if (!currentPaymentVoucher.value?.fileId) {
    // 如果没有当前凭证，直接显示上传组件
    currentPaymentVoucher.value = null;
    return;
  }

  const fileId = currentPaymentVoucher.value.fileId;

  try {
    // 删除当前文件
    await deleteFileApi(fileId);
    // 清空相关数据，这样上传组件就会显示
    townPaymentForm.paymentVoucherFileId = null;
    currentPaymentVoucher.value = null;
    // 从新上传文件列表中移除
    const index = newUploadedFileIds.value.indexOf(fileId);
    if (index > -1) {
      newUploadedFileIds.value.splice(index, 1);
    }
    Message.success("已清除当前凭证，请重新上传");
  } catch (error) {
    console.error("删除当前凭证失败:", error);
    Message.error("删除当前凭证失败");
  }
};

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const methodItem = paymentMethods.value.find(
    (item) => String(item.dictKey) === String(method)
  );
  return methodItem ? methodItem.dictValue : method || "-";
};

// 查看支付凭证
const viewPaymentVoucher = (record) => {
  if (record?.fileId && record?.file) {
    const voucher = {
      fileId: record.fileId,
      fileName: record.file.fileName,
      fileSize: record.file.fileSize,
      fileUrl: record.file.fileUrl,
    };

    if (isImageFile(voucher.fileName)) {
      // 如果是图片，直接预览
      previewPaymentVoucher(voucher);
    } else {
      // 如果不是图片，下载文件
      downloadPaymentVoucher(voucher);
    }
  } else {
    Message.warning("支付凭证文件不存在");
  }
};

// 初始化数据
const initializeData = async () => {
  if (!props.subsidyApplicationId) return;

  try {
    loading.value = true;

    // 加载支付通知数据（包含支付记录）
    const noticeResponse =
      await getSubsidyApplicationPayNoticeListBySubsidyApplicationIdApi(
        props.subsidyApplicationId
      );
    if (noticeResponse) {
      // 确保paymentNotices.value始终是数组
      paymentNotices.value = Array.isArray(noticeResponse)
        ? noticeResponse
        : [];
      console.log("支付通知数据:", paymentNotices.value);
    } else {
      paymentNotices.value = [];
      Message.error("获取支付通知失败");
    }

    // 初始化时清空支付记录，等待用户选择支付通知
    townPaymentRecords.value = [];
  } catch (error) {
    console.error("初始化数据失败:", error);
    Message.error("初始化数据失败");
  } finally {
    loading.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  initializeData();
});

// 刷新数据
const refreshData = async () => {
  try {
    refreshLoading.value = true;
    const currentSelectedNotice = selectedNoticeId.value;
    await initializeData();
    // 如果有选中的支付通知，重新加载镇街支付明细和支付记录
    if (currentSelectedNotice) {
      selectedNoticeId.value = currentSelectedNotice;
      await handleNoticeChange(currentSelectedNotice);
    }
    Message.success("数据刷新成功");
  } catch (error) {
    console.error("刷新数据失败:", error);
    Message.error("刷新数据失败");
  } finally {
    refreshLoading.value = false;
  }
};

// 组件卸载时清理定时器
onUnmounted(() => {
  if (noticeChangeTimer) {
    clearTimeout(noticeChangeTimer);
  }
});
</script>

<style scoped>
.payment-management {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.payment-records {
  background: white;
  border-radius: 8px;
  padding: 20px;
  flex: 1;
  width: 100%;
  box-sizing: border-box;
}

.records-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.records-title {
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  border: 1px solid #e5e6eb;
}

.section-left {
  display: flex;
  align-items: center;
}

.section-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
}

/* 镇街支付明细布局优化 */
.town-payment-details {
  width: 100%;
}

.town-details-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  width: 100%;
  margin-top: 16px;
}

.town-detail-card {
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  border: 1px solid #e5e6eb;
  border-radius: 6px;
  background: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  transition: all 0.2s ease;
}

.town-detail-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
  border-color: #c9cdd4;
}

.town-detail-card :deep(.arco-card-header) {
  padding: 14px 16px;
  background: #fafbfc;
  font-weight: 600;
  font-size: 15px;
  border-bottom: 1px solid #e5e6eb;
  color: #1d2129;
}

.town-detail-card :deep(.arco-card-body) {
  padding: 16px;
  width: 100%;
  box-sizing: border-box;
}

/* 镇街信息单行展示样式 */
.town-info-line {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 14px;
  padding: 10px 12px;
  background: #f7f8fa;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #4e5969;
  white-space: nowrap;
}

.info-item strong {
  color: #1d2129;
  font-weight: 600;
}

@media (max-width: 768px) {
  .town-info-line {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .town-info-line .separator {
    display: none;
  }
}

/* 支付记录样式优化 */
.town-payment-records {
  margin-top: 14px;
}

.town-payment-records h4 {
  margin: 0 0 10px 0;
  font-size: 13px;
  font-weight: 600;
  color: #1d2129;
  padding-bottom: 6px;
  border-bottom: 1px solid #e5e6eb;
}

.payment-record-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.payment-record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  background: #fafbfc;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.payment-record-item:hover {
  background: #f2f3f5;
  border-color: #c9cdd4;
}

.record-content {
  flex: 1;
}

.record-info {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
  font-size: 13px;
  color: #4e5969;
}

.record-info strong {
  color: #1d2129;
  font-weight: 600;
}

.separator {
  color: #c9cdd4;
  margin: 0 3px;
  font-size: 12px;
}

.record-remark {
  color: #4e5969;
  font-style: italic;
}

.record-actions {
  flex-shrink: 0;
  margin-left: 12px;
}

@media (max-width: 768px) {
  .payment-record-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .record-actions {
    margin-left: 0;
    align-self: flex-end;
  }

  .record-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .separator {
    display: none;
  }
}

/* 金额文本样式优化 */
.current-amount-text {
  color: #00b42a;
  font-weight: 600;
  font-size: 14px;
}

/* 镇街支付明细相关样式 */
.town-payment-form {
  margin-top: 20px;
  width: 100%;
}

.town-payment-form h4 {
  margin-bottom: 16px;
  color: #1d2129;
  font-weight: 600;
  font-size: 16px;
}

.town-payment-items {
  margin-bottom: 20px;
  width: 100%;
}

.town-payment-item {
  margin-bottom: 16px;
  width: 100%;
}

.town-payment-item :deep(.arco-card) {
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  width: 100%;
  box-sizing: border-box;
}

.town-payment-item :deep(.arco-card-header) {
  background-color: #f7f8fa;
  border-bottom: 1px solid #e5e6eb;
  font-weight: 600;
  color: #1d2129;
}

.town-payment-item :deep(.arco-form-item) {
  margin-bottom: 16px;
  width: 100%;
}

.town-payment-item :deep(.arco-form-item-label) {
  font-weight: 500;
  color: #4e5969;
}

.town-payment-item :deep(.arco-form-item-wrapper) {
  width: 100%;
}

.town-payment-item :deep(.arco-input),
.town-payment-item :deep(.arco-select),
.town-payment-item :deep(.arco-textarea) {
  width: 100%;
}

.notice-details-preview {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 16px;
}

.notice-details-header h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-weight: 600;
}

.town-payment-details-table {
  background: white;
  border-radius: 6px;
  overflow: hidden;
  width: 100%;
  box-sizing: border-box;
}

.payment-details-table {
  border: 1px solid #e8e8e8;
  width: 100%;
}

.payment-details-table :deep(.arco-table-th) {
  background: #fafafa;
  font-weight: 600;
  color: #333;
}

.payment-details-table :deep(.arco-table-td) {
  padding: 8px 12px;
}

.amount-text {
  color: #1890ff;
  font-weight: 500;
}

.current-amount-text {
  color: #52c41a;
  font-weight: 600;
}

.payment-summary {
  background: #f0f9ff;
  padding: 12px 16px;
  border-radius: 6px;
  border: 1px solid #bae7ff;
}

.summary-descriptions {
  background-color: #f7f8fa;
  border-radius: 6px;
  padding: 16px;
}

.summary-descriptions :deep(.arco-descriptions-item-label) {
  font-weight: 600;
  color: #333;
}

.summary-text {
  color: #666;
  font-weight: 500;
}

.summary-amount-text {
  color: #1890ff;
  font-weight: 600;
}

.current-total-amount-text {
  color: #52c41a;
  font-weight: 700;
  font-size: 16px;
}

/* 附件相关样式 */
.existing-file-section {
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  padding: 10px;
  background-color: #f7f8fa;
}

.existing-file-title {
  font-size: 13px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 6px;
}

.existing-file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 10px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
}

.file-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.file-icon {
  margin-right: 6px;
  color: #86909c;
}

.file-details {
  flex: 1;
}

.file-name {
  margin: 0;
  font-size: 13px;
  color: #1d2129;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
}

.file-size {
  margin: 0;
  font-size: 11px;
  color: #86909c;
}

.file-actions {
  display: flex;
  gap: 3px;
}

.upload-tip {
  display: flex;
  align-items: center;
  margin-top: 6px;
  padding: 6px 10px;
  background-color: #f2f3f5;
  border-radius: 4px;
  font-size: 11px;
  color: #86909c;
}

.tip-icon {
  margin-right: 4px;
  font-size: 12px;
}

.preview-content {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.mb-4 {
  margin-bottom: 14px;
}

.mb-3 {
  margin-bottom: 10px;
}

.mt-3 {
  margin-top: 10px;
}

:deep(.arco-statistic-title) {
  font-size: 13px;
  color: #86909c;
}

:deep(.arco-statistic-content) {
  font-size: 18px;
  font-weight: 600;
}

/* 上传区域样式 */
.upload-section {
  padding: 16px;
  background: #fafbfc;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.upload-section:hover {
  border-color: #165dff;
  background: #f8f9ff;
}

/* 支付凭证展示样式 */
.existing-voucher-section {
  margin-top: 12px;
  padding: 12px;
  background: #fafbfc;
  border: 1px solid #e5e6eb;
  border-radius: 6px;
}

.existing-voucher-title {
  font-size: 14px;
  font-weight: 500;
  color: #1d2129;
  margin-bottom: 8px;
}

.existing-voucher-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: white;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
}

.voucher-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.voucher-icon {
  margin-right: 8px;
  color: #86909c;
  font-size: 16px;
}

.voucher-details {
  flex: 1;
  min-width: 0;
}

.voucher-name {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #1d2129;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.voucher-size {
  margin: 0;
  font-size: 12px;
  color: #86909c;
}

.voucher-actions {
  display: flex;
  gap: 8px;
  margin-left: 12px;
}

.voucher-actions .arco-btn {
  padding: 4px 8px;
  font-size: 12px;
}

/* 预览弹窗样式 */
.preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .town-details-list {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .payment-management {
    padding: 12px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    padding: 12px 14px;
  }

  .section-left {
    width: 100%;
  }

  .section-header .arco-select {
    width: 100%;
    margin-left: 0;
    margin-top: 8px;
  }

  .town-info-line {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .separator {
    display: none;
  }

  .info-item {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .payment-management {
    padding: 8px;
  }

  .town-detail-card :deep(.arco-card-header) {
    padding: 10px 12px;
  }

  .town-detail-card :deep(.arco-card-body) {
    padding: 12px;
  }

  .payment-record-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .record-actions {
    margin-left: 0;
    width: 100%;
  }

  .record-actions :deep(.arco-space) {
    width: 100%;
    justify-content: flex-end;
  }
}

/* 全局宽度优化 */
:deep(.arco-table) {
  width: 100%;
}

:deep(.arco-card-body) {
  width: 100%;
  box-sizing: border-box;
}

:deep(.arco-row) {
  width: 100%;
}

:deep(.arco-col) {
  width: 100%;
}

:deep(.arco-form) {
  width: 100%;
}

:deep(.arco-descriptions) {
  width: 100%;
}

/* 按钮组优化 */
.records-header,
.section-header {
  width: 100%;
  box-sizing: border-box;
}
</style>
